package com.hr.hrto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hr.hrto.common.BaseContext;
import com.hr.hrto.common.CustomException;
import com.hr.hrto.common.R;
import com.hr.hrto.domain.*;
import com.hr.hrto.dto.OrderDto;
import com.hr.hrto.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 黄瑞
 * @Date: 2022/07/14/15:55
 * @Description:
 * @version:1.0
 */
@RequestMapping("/order")
@RestController
@Slf4j
public class OrderControllrt {

    @Autowired
    private OrderService orderService;

    @Resource
    private OrderDertailService OrderDetailService;

    @Resource
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;
    @Autowired
    SetMealService setMealService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @PutMapping()
    public R<String> orderStatus(@RequestBody Orders orders) {
        // 修改状态
        orderService.updateById(orders);
        return R.success("修改成功");
    }

//    @GetMapping("/page")
//    public R<Page> page(int page, int pageSize){
//        //分页构造器
//        Page<Orders> pageinfo =new Page<>(page,pageSize);
//        //条件构造器
//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//        //添加排除条件，根据sort进行排序
//        queryWrapper.orderByDesc(Orders::getOrderTime);
//        //进行分页查询
//        orderService.page(pageinfo, queryWrapper);
//        return R.success(pageinfo);
//    }

    /**
     * 后端管理查询查询订单
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, String number,
                                @DateTimeFormat(pattern = "yyyy-mm-dd HH:mm:ss") Date beginTime,
                                @DateTimeFormat(pattern = "yyyy-mm-dd HH:mm:ss") Date endTime) {
        log.info("beginTime={},endTime={}", beginTime, endTime);
        // 构建订单分页对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        // 构造条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
        // 模糊查询根据订单号或者时间间隔查询
        // SELECT * FROM Order where number like ? or order_time between ? and ?
        queryWrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        if (beginTime != null) {
            queryWrapper.between(Orders::getOrderTime, beginTime, endTime);
        }
        // 时间降序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        // 封装为分页对象
        orderService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize){
        log.info("page = {},pageSize = {}",page,pageSize);

        //构造分页构造器
        Page<Orders> pageInfo = new Page(page,pageSize);
        Page<OrderDto> ordersDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getCheckoutTime);

        //执行查询
        orderService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");

        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto ordersDto = new OrderDto();

            BeanUtils.copyProperties(item,ordersDto);

            Long orderid = item.getId();//订单号

            //根据订单号查询订单详情
            //构造条件构造器
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //添加过滤条件
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderid);
            //执行查询
            List<OrderDetail> orderDetailList = OrderDetailService.list(lambdaQueryWrapper);

            ordersDto.setOrderDetails(orderDetailList);
            ordersDto.setSumNum(orderDetailList.size());

            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }
    //客户端点击再来一单
    /**
     * 前端点击再来一单是直接跳转到购物车的，所以为了避免数据有问题，再跳转之前我们需要把购物车的数据给清除
     * ①通过orderId获取订单明细
     * ②把订单明细的数据的数据塞到购物车表中，不过在此之前要先把购物车表中的数据给清除(清除的是当前登录用户的购物车表中的数据)，
     * 不然就会导致再来一单的数据有问题；
     * (这样可能会影响用户体验，但是对于外卖来说，用户体验的影响不是很大，电商项目就不能这么干了)
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String,String> map){
        String ids = map.get("id");

        long id = Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        //获取该订单对应的所有的订单明细表
        List<OrderDetail> orderDetailList = OrderDetailService.list(queryWrapper);

        //通过用户id把原来的购物车给清空，这里的clean方法是视频中讲过的,建议抽取到service中,那么这里就可以直接调用了
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper1);
        //shoppingCartService.clean();

        //获取用户id
        LambdaQueryWrapper<Dish> queryWrapper2 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> queryWrapper3 = new LambdaQueryWrapper<>();
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //把从order表中和order_details表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                try {
                    queryWrapper2.eq(Dish::getId,dishId);
                    int dishStatus = dishService.getOne(queryWrapper2).getStatus();
                    if (dishStatus != 1) {
                        throw new CustomException("此商品已下架");
                    }
                } catch (Exception e) {
                    throw new CustomException("此商品已下架");
                }
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                try {
                    queryWrapper3.eq(Setmeal::getId,setmealId);
                    Integer dishStatus = setMealService.getOne(queryWrapper3).getStatus();
                    if (dishStatus != 1) {
                        throw new CustomException("此商品已下架");
                    }
                } catch (Exception e) {
                    throw new CustomException("此商品已下架");
                }
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //把携带数据的购物车批量插入购物车表  这个批量保存的方法要使用熟练！！！
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }




}
